package com.ttx.zookeeper.cluster;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListener;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.CountDownLatch;

/**
 * @author TimFruit
 * @date 20-2-24 下午11:23
 */
public class CuratorWorker {


    private static final String clusterPath="/cluster";
    private static final String nodesPath=clusterPath+"/nodes";
    private static final String confPath=clusterPath+"/conf";



    public static void main(String[] args) throws InterruptedException {

        String connectString="127.0.0.1:2181," +
                "127.0.0.1:2182," +
                "127.0.0.1:2183";

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
        CuratorFramework client = CuratorFrameworkFactory.newClient(connectString, retryPolicy);
        client.start();



        final CountDownLatch cdl=new CountDownLatch(1);

        LeaderSelectorListener listener = new LeaderSelectorListenerAdapter()
        {
            public void takeLeadership(CuratorFramework client) throws Exception
            {
                // this callback will get called when you are the leader
                // do whatever leader work you need to and only exit
                // this method when you want to relinquish leadership
                System.out.println("成为leader...");
                work();
            }
        };

        LeaderSelector selector = new LeaderSelector(client, nodesPath, listener);
        selector.autoRequeue();  // not required, but this is behavior that you will probably expect
        selector.start();




        //
        System.out.println("standby...");
        cdl.await();




    }



    public static void work() throws InterruptedException {
        System.out.println("假装工作(等待)...");
        Thread.sleep(Long.MAX_VALUE);
    }
}
